package org.shs.user.service;

import static org.shs.common.config.SystemInitializer.app_msgs;

import org.apache.log4j.Logger;
import org.shs.common.dao.CommonDAOFactory;
import org.shs.user.dao.IUserDAO;
import org.shs.user.form.LoginForm;
import org.shs.user.model.UserModel;

/**
 * This class will be responsible for data manipulation and
 * abstraction of the DAO and Presentation layer for the 
 * User related module.
 * <br/>
 * <br/><b>Created:</b>&nbsp;&nbsp; 12-Nov-2008 00:24:28
 *
 * @author anirvan
 *
 */
public class UserService
{
   /**
    * The reference for the DAO interface associated with this 
    * service class.
    */
   private IUserDAO userDao = null;
   
   /**
    * The logger instance to be used
    */
   private static Logger logger = Logger.getLogger(UserService.class);
   
   /**
    * The default constructor
    */
   public UserService()
   {
      try
      {
         //Initialize the DAO instance
         userDao = (IUserDAO)CommonDAOFactory
                        .getDAO(app_msgs.getMessage("user.daoImpl"));
      }
      catch (Exception e) 
      {
         logger.error("[Possible cause] No key present for {user.daoImpl}.", e);
      }
   }
   
   /**
    * Validate the credentials of the user trying to log into
    * the system
    * @param userData The bean encapsulating the loggers details
    * @return bean model containing the user's data 
    */
   public UserModel validateUser(LoginForm userData) throws Exception
   {
      UserModel user = null;
      
      try
      {
         user = userDao.validateUser(userData);
         if(user != null)
         {
            user.setMessage(app_msgs.getMessage("msg.welcome", 
                                                user.getUsername()));
            user.setIsValidated(true);
            
         }
         else
         {
            user = new UserModel();
            user.setError(true);
            user.setMessage(app_msgs.getMessage("msg.loginFailure"));
         }
      }
      catch(Exception e)
      {
         logger.error("User could not be validated.", e);
         throw new Exception("User could not be validated.", e);
      }
      return user;
   }
}
